package com.crypto;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class ECDSASign implements SignFunc {

    /**
     * 用私钥进行签名
     * @param privateKey
     * @param message
     * @return
     */
    @Override
    public byte[] sign(PrivateKey privateKey, byte[] message){
        try {
            Signature s1 = Signature.getInstance("SHA1withECDSA");
            s1.initSign(privateKey);
            s1.update(message);
            byte[] sign = s1.sign();
            return sign;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return new byte[0];
    }

    /**
     * 验证签名
     *
     * @param signature
     * @param message
     * @param publicKey
     * @return
     */
    @Override
    public Boolean verify(byte[] signature, byte[] message, PublicKey publicKey) {
        try {
            Signature s2 = Signature.getInstance("SHA1withECDSA");
            s2.initVerify(publicKey);
            s2.update(message);
            return s2.verify(signature);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}
